package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/common/eventtype"
)

type (
	AlarmHistroy eventtype.AlarmHistroy

	AlarmHistoryModel struct {
		db *gorm.DB
	}
)

func NewAlarmHistroyModel(db *gorm.DB) *AlarmHistoryModel {
	return &AlarmHistoryModel{
		db,
	}
}

func (m *AlarmHistoryModel) FindAllCount(stationId string, startTime string, endTime string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&AlarmHistroy{})
	if stationId != "" {
		dbSession.Where("station_id = ?", stationId)
	}
	if startTime != "" && endTime != "" {
		dbSession.Where("alarm_time >= ?", startTime)
		dbSession.Where("alarm_time <= ?", endTime)
	}
	err := dbSession.Count(&total).Error
	return total, err
}

func (m *AlarmHistoryModel) FindAll(stationId string, page int, size int, startTime string, endTime string) ([]AlarmHistroy, error) {
	var list []AlarmHistroy
	dbSession := m.db.Model(&AlarmHistroy{})
	if stationId != "" {
		dbSession.Where("station_id = ?", stationId)
	}
	if startTime != "" && endTime != "" {
		dbSession.Where("alarm_time >= ?", startTime)
		dbSession.Where("alarm_time <= ?", endTime)
	}
	dbSession.Limit(size).Offset((page - 1) * size)
	dbSession.Find(&list)
	err := dbSession.Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []AlarmHistroy{}, nil
	}
	return append([]AlarmHistroy{}, list...), err
}
func (m *AlarmHistoryModel) FindByStationByIdsCount(stationIds []string, startTime string, endTime string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&AlarmHistroy{})
	//dbSession.Joins("JOIN thing_stations ON stations.uid = thing_stations.thing_id AND stations.uid in ?", stationIds)
	//dbSession.Joins("JOIN alarm_histroys ON alarm_histroys.t_id = thing_stations.thing_id")
	dbSession.Where("station_id in ?", stationIds)
	if startTime != "" && endTime != "" {
		dbSession.Where("alarm_time >= ?", startTime)
		dbSession.Where("alarm_time <= ?", endTime)
	}
	dbSession.Count(&total)
	err := dbSession.Error
	return total, err
}

func (m *AlarmHistoryModel) FindByStationByIdsList(stationIds []string, page, size int, startTime string, endTime string) ([]AlarmHistroy, error) {
	var alarmList []AlarmHistroy
	dbSession := m.db.Model(&AlarmHistroy{})
	//dbSession.Joins("JOIN thing_stations ON stations.uid = thing_stations.thing_id AND stations.uid in ?", stationIds)
	//dbSession.Joins("JOIN alarm_histroys ON alarm_histroys.t_id = thing_stations.thing_id")
	dbSession.Where("station_id in ?", stationIds)
	if startTime != "" && endTime != "" {
		dbSession.Where("alarm_time >= ?", startTime)
		dbSession.Where("alarm_time <= ?", endTime)
	}
	dbSession.Limit(size).Offset((page - 1) * size)
	dbSession.Find(&alarmList)
	err := dbSession.Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []AlarmHistroy{}, nil
	}
	return append([]AlarmHistroy{}, alarmList...), err
}
